<template>
  <div class="percentage-calculator-tool">
    <div class="tool-header">
      <h1>百分比计算器</h1>
      <p>各种百分比计算工具</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 计算器主体 -->
        <el-col :span="16">
          <div class="calculator-section">
            <!-- 基本百分比计算 -->
            <div class="calculation-type">
              <h3>基本百分比计算</h3>
              <div class="percentage-inputs">
                <div class="input-group">
                  <label>数值：</label>
                  <el-input-number
                    v-model="baseValue"
                    :precision="2"
                    :step="0.1"
                    size="large"
                    placeholder="输入数值"
                    @change="calculateBasicPercentage"
                  />
                </div>
                <div class="input-group">
                  <label>百分比：</label>
                  <el-input-number
                    v-model="percentage"
                    :precision="2"
                    :step="1"
                    :min="0"
                    :max="1000"
                    size="large"
                    placeholder="输入百分比"
                    @change="calculateBasicPercentage"
                  />
                  <span class="unit">%</span>
                </div>
              </div>
              
              <div class="result-display" v-if="basicResult">
                <h4>计算结果：</h4>
                <div class="result-item">
                  <div class="result-formula">{{ basicResult.formula }}</div>
                  <div class="result-value">= {{ basicResult.result }}</div>
                </div>
              </div>
            </div>
            
            <!-- 百分比变化计算 -->
            <div class="calculation-type">
              <h3>百分比变化计算</h3>
              <div class="change-inputs">
                <div class="input-group">
                  <label>原始值：</label>
                  <el-input-number
                    v-model="originalValue"
                    :precision="2"
                    :step="0.1"
                    size="large"
                    placeholder="输入原始值"
                    @change="calculatePercentageChange"
                  />
                </div>
                <div class="input-group">
                  <label>新值：</label>
                  <el-input-number
                    v-model="newValue"
                    :precision="2"
                    :step="0.1"
                    size="large"
                    placeholder="输入新值"
                    @change="calculatePercentageChange"
                  />
                </div>
              </div>
              
              <div class="result-display" v-if="changeResult">
                <h4>计算结果：</h4>
                <div class="result-item">
                  <div class="result-formula">{{ changeResult.formula }}</div>
                  <div class="result-value" :class="{ 'positive': changeResult.isPositive, 'negative': !changeResult.isPositive }">
                    = {{ changeResult.result }}%
                  </div>
                  <div class="result-description">{{ changeResult.description }}</div>
                </div>
              </div>
            </div>
            
            <!-- 百分比与分数转换 -->
            <div class="calculation-type">
              <h3>百分比与分数转换</h3>
              <div class="conversion-inputs">
                <div class="input-group">
                  <label>百分比：</label>
                  <el-input-number
                    v-model="percentForConversion"
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    :max="100"
                    size="large"
                    placeholder="输入百分比"
                    @change="calculateConversion"
                  />
                  <span class="unit">%</span>
                </div>
                <div class="input-group">
                  <label>分数：</label>
                  <el-input-number
                    v-model="fractionNumerator"
                    :precision="0"
                    :step="1"
                    :min="1"
                    size="large"
                    placeholder="分子"
                    @change="calculateConversion"
                  />
                  <span class="separator">/</span>
                  <el-input-number
                    v-model="fractionDenominator"
                    :precision="0"
                    :step="1"
                    :min="1"
                    size="large"
                    placeholder="分母"
                    @change="calculateConversion"
                  />
                </div>
              </div>
              
              <div class="result-display" v-if="conversionResult">
                <h4>转换结果：</h4>
                <div class="conversion-result">
                  <div class="result-item">
                    <div class="result-label">百分比：</div>
                    <div class="result-value">{{ conversionResult.percentage }}%</div>
                  </div>
                  <div class="result-item">
                    <div class="result-label">分数：</div>
                    <div class="result-value">{{ conversionResult.fraction }}</div>
                  </div>
                  <div class="result-item">
                    <div class="result-label">小数：</div>
                    <div class="result-value">{{ conversionResult.decimal }}</div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 折扣计算 -->
            <div class="calculation-type">
              <h3>折扣计算</h3>
              <div class="discount-inputs">
                <div class="input-group">
                  <label>原价：</label>
                  <el-input-number
                    v-model="originalPrice"
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    size="large"
                    placeholder="输入原价"
                    @change="calculateDiscount"
                  />
                </div>
                <div class="input-group">
                  <label>折扣率：</label>
                  <el-input-number
                    v-model="discountRate"
                    :precision="1"
                    :step="1"
                    :min="0"
                    :max="100"
                    size="large"
                    placeholder="输入折扣率"
                    @change="calculateDiscount"
                  />
                  <span class="unit">%</span>
                </div>
              </div>
              
              <div class="result-display" v-if="discountResult">
                <h4>计算结果：</h4>
                <div class="discount-result">
                  <div class="result-item">
                    <div class="result-label">折扣金额：</div>
                    <div class="result-value">¥{{ discountResult.discountAmount }}</div>
                  </div>
                  <div class="result-item">
                    <div class="result-label">最终价格：</div>
                    <div class="result-value">¥{{ discountResult.finalPrice }}</div>
                  </div>
                  <div class="result-item">
                    <div class="result-label">节省金额：</div>
                    <div class="result-value save-amount">¥{{ discountResult.discountAmount }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 工具和说明 -->
        <el-col :span="8">
          <div class="tools-section">
            <div class="section-header">
              <h3>常用百分比</h3>
            </div>
            
            <div class="common-percentages">
              <div 
                v-for="item in commonPercentages" 
                :key="item.value"
                class="percentage-item"
                @click="setCommonPercentage(item.value)"
              >
                <div class="percentage-value">{{ item.value }}%</div>
                <div class="percentage-desc">{{ item.description }}</div>
              </div>
            </div>
          </div>
          
          <div class="help-section">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>使用说明</span>
                </div>
              </template>
              
              <div class="help-content">
                <h4>计算类型：</h4>
                <ul>
                  <li><strong>基本计算：</strong> 计算数值的百分比</li>
                  <li><strong>变化计算：</strong> 计算两个值之间的百分比变化</li>
                  <li><strong>转换计算：</strong> 百分比与分数、小数之间的转换</li>
                  <li><strong>折扣计算：</strong> 计算折扣后的价格</li>
                </ul>
                
                <h4>计算公式：</h4>
                <ul>
                  <li><strong>基本：</strong> 数值 × 百分比% = 结果</li>
                  <li><strong>变化：</strong> (新值 - 原值) / 原值 × 100%</li>
                  <li><strong>转换：</strong> 百分比% = 分数 × 100%</li>
                  <li><strong>折扣：</strong> 最终价格 = 原价 × (1 - 折扣率%)</li>
                </ul>
                
                <h4>注意事项：</h4>
                <div class="warning">
                  <p>⚠️ 百分比变化可能为负数，表示减少</p>
                  <p>⚠️ 分数转换会自动约分到最简形式</p>
                  <p>⚠️ 折扣计算中折扣率不能超过100%</p>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

const baseValue = ref(100)
const percentage = ref(20)
const originalValue = ref(100)
const newValue = ref(120)
const percentForConversion = ref(25)
const fractionNumerator = ref(1)
const fractionDenominator = ref(4)
const originalPrice = ref(100)
const discountRate = ref(20)

const basicResult = ref(null)
const changeResult = ref(null)
const conversionResult = ref(null)
const discountResult = ref(null)

const commonPercentages = [
  { value: 10, description: '一成' },
  { value: 20, description: '二成' },
  { value: 25, description: '四分之一' },
  { value: 50, description: '一半' },
  { value: 75, description: '四分之三' },
  { value: 100, description: '全部' }
]

const calculateBasicPercentage = () => {
  if (baseValue.value === null || percentage.value === null) return
  
  const result = (baseValue.value * percentage.value) / 100
  basicResult.value = {
    formula: `${baseValue.value} × ${percentage.value}%`,
    result: result.toFixed(2)
  }
}

const calculatePercentageChange = () => {
  if (originalValue.value === null || newValue.value === null) return
  
  if (originalValue.value === 0) {
    ElMessage.warning('原始值不能为0')
    return
  }
  
  const change = ((newValue.value - originalValue.value) / originalValue.value) * 100
  const isPositive = change >= 0
  
  changeResult.value = {
    formula: `(${newValue.value} - ${originalValue.value}) / ${originalValue.value} × 100%`,
    result: change.toFixed(2),
    isPositive,
    description: isPositive ? '增加了' : '减少了'
  }
}

const calculateConversion = () => {
  if (percentForConversion.value !== null) {
    // 从百分比计算分数
    const decimal = percentForConversion.value / 100
    const fraction = decimalToFraction(decimal)
    
    conversionResult.value = {
      percentage: percentForConversion.value.toFixed(2),
      fraction: fraction,
      decimal: decimal.toFixed(4)
    }
  } else if (fractionNumerator.value !== null && fractionDenominator.value !== null) {
    // 从分数计算百分比
    const decimal = fractionNumerator.value / fractionDenominator.value
    const percentage = decimal * 100
    
    conversionResult.value = {
      percentage: percentage.toFixed(2),
      fraction: `${fractionNumerator.value}/${fractionDenominator.value}`,
      decimal: decimal.toFixed(4)
    }
  }
}

const decimalToFraction = (decimal) => {
  const tolerance = 1e-6
  let h1 = 1, h2 = 0, k1 = 0, k2 = 1
  let b = decimal
  
  do {
    let a = Math.floor(b)
    let aux = h1
    h1 = a * h1 + h2
    h2 = aux
    aux = k1
    k1 = a * k1 + k2
    k2 = aux
    b = 1 / (b - a)
  } while (Math.abs(decimal - h1 / k1) > decimal * tolerance)
  
  return `${h1}/${k1}`
}

const calculateDiscount = () => {
  if (originalPrice.value === null || discountRate.value === null) return
  
  const discountAmount = (originalPrice.value * discountRate.value) / 100
  const finalPrice = originalPrice.value - discountAmount
  
  discountResult.value = {
    discountAmount: discountAmount.toFixed(2),
    finalPrice: finalPrice.toFixed(2)
  }
}

const setCommonPercentage = (value) => {
  percentage.value = value
  percentForConversion.value = value
  discountRate.value = value
  calculateBasicPercentage()
  calculateConversion()
  calculateDiscount()
  ElMessage.success(`已设置为${value}%`)
}

// 初始化计算
calculateBasicPercentage()
calculatePercentageChange()
calculateConversion()
calculateDiscount()
</script>

<style scoped>
.percentage-calculator-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.calculator-section,
.tools-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.calculation-type {
  margin-bottom: 40px;
  padding-bottom: 30px;
  border-bottom: 1px solid #e9ecef;
}

.calculation-type:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.calculation-type h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.3rem;
}

.percentage-inputs,
.change-inputs,
.conversion-inputs,
.discount-inputs {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.input-group {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 10px;
}

.input-group label {
  min-width: 60px;
  font-weight: 500;
  color: #666;
}

.input-group .el-input-number {
  flex: 1;
}

.unit {
  color: #666;
  font-weight: 500;
}

.separator {
  color: #666;
  font-weight: bold;
  font-size: 1.2rem;
}

.result-display {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
}

.result-display h4 {
  color: #333;
  margin-bottom: 15px;
  font-size: 1.1rem;
}

.result-item {
  background: white;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  margin-bottom: 10px;
}

.result-item:last-child {
  margin-bottom: 0;
}

.result-formula {
  font-size: 1.1rem;
  color: #666;
  margin-bottom: 8px;
  font-family: 'Courier New', monospace;
}

.result-value {
  font-size: 1.5rem;
  font-weight: bold;
  color: #667eea;
}

.result-value.positive {
  color: #28a745;
}

.result-value.negative {
  color: #dc3545;
}

.result-description {
  font-size: 0.9rem;
  color: #666;
  margin-top: 5px;
}

.conversion-result,
.discount-result {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
}

.conversion-result .result-item,
.discount-result .result-item {
  text-align: center;
}

.result-label {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 5px;
}

.save-amount {
  color: #28a745 !important;
}

.section-header {
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.common-percentages {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.percentage-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.percentage-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.percentage-value {
  font-size: 1.2rem;
  font-weight: bold;
  color: #667eea;
  margin-bottom: 5px;
}

.percentage-desc {
  font-size: 0.9rem;
  color: #666;
}

.help-section {
  margin-top: 20px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.help-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.help-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.help-content li {
  margin-bottom: 5px;
}

.warning {
  background: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
  margin: 15px 0;
}

.warning p {
  margin: 5px 0;
  color: #856404;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .percentage-inputs,
  .change-inputs,
  .conversion-inputs,
  .discount-inputs {
    flex-direction: column;
  }
  
  .input-group {
    flex-direction: column;
    align-items: stretch;
  }
  
  .input-group label {
    min-width: auto;
  }
  
  .conversion-result,
  .discount-result {
    grid-template-columns: 1fr;
  }
  
  .common-percentages {
    grid-template-columns: 1fr;
  }
}
</style>
